/**
 * 
 */
package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.OnPainPointSelectListener;
import com.jdy.haoduoai.adapter.PainPointAdapter;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PainPointItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

//import com.jdy.haoduoai.R;

/**
 * @author zp 2016-11-29 上午11:30:03
 */
public class PainPointSelectActivity extends BaseActivity implements
    OnClickListener {

  private static final String TAG = PainPointSelectActivity.class
      .getSimpleName();

  @InjectView(id = R.id.commit_btn, click = true)
  private Button mCommitBtn;

  @InjectView(id = R.id.painpoint_list)
  private ListView mPainpointLv;

  private PainPointAdapter mPainPointAdapter;

  private ArrayList<Integer> mSelectedPainPointIds;

  private ArrayList<PainPointItem> mPainPointList;
  private ArrayList<PainPointItem> mPainPointListSelect;

  private boolean fromFillInfoPage;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.painpoint_select_layout);

    setTitle("习惯养成大纲");

    Intent intent = getIntent();
    if (intent != null) {
      fromFillInfoPage = intent.getBooleanExtra("fromFillInfoPage", false);
    }

    mSelectedPainPointIds = new ArrayList<Integer>();

    checkBabyAge();

    getPainpointList();

    showloading("");

  }

  private void getPainpointList() {

    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {

        if (result.isSuccess()) {
          // showToast(result.data);//volume

          mSelectedPainPointIds.clear();

          ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  PainPointItem.class);

          mPainPointList = new ArrayList<PainPointItem>();

          mPainPointAdapter = new PainPointAdapter(activity, mPainPointList);

          for (PainPointItem ppi : list) {
            mPainPointList.add(ppi);
            if (ppi.selected) {
              mSelectedPainPointIds.add(ppi.id);
            }
          }

          mCommitBtn.setText("提交好习惯培养计划 (已选 " + mSelectedPainPointIds.size()
              + "个)");

          mPainPointAdapter.setSelectedList(mSelectedPainPointIds);

          mPainPointAdapter
              .setPainPointSelectListener(new OnPainPointSelectListener() {

                @Override
                public void onPainPointSelect(int id, boolean selected) {
                  // TODO Auto-generated method stub

                  if (selected) {
                    if (!mSelectedPainPointIds.contains(id)) {
                      mSelectedPainPointIds.add(id);
                    }

                    mCommitBtn.setText("提交好习惯培养计划 (已选 "
                        + mSelectedPainPointIds.size() + "个)");
                  } else {
                    if (mSelectedPainPointIds.contains(id)) {

                      int index = mSelectedPainPointIds.indexOf(id);

                      mSelectedPainPointIds.remove(index);

                      mCommitBtn.setText("提交好习惯培养计划 (已选 "
                          + mSelectedPainPointIds.size() + "个)");
                    }
                  }

                }
              });

          mPainpointLv.setAdapter(mPainPointAdapter);

          mPainpointLv.setItemsCanFocus(true);

          mPainpointLv.setFocusable(false);

          mPainpointLv.setFocusableInTouchMode(false);

          mPainpointLv.setClickable(false);

          mPainPointAdapter.notifyDataSetChanged();
        }

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        if (mGlobalLeUser != null) {
          param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        } else {
          LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
          if (lu == null) {
            lu = Tools.restoreLeUser();
          }
          param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        }

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.GET_PAINPOINT_LIST_GET, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();

  }

  private String convertList2String(ArrayList<Integer> ids) {
    String result = "";
    if (ids != null) {
      if (ids.size() == 0) {
        return "0";
      }
      int i = 0;
      int size = ids.size();
      for (; i < size; i++) {
        result += ids.get(i);
        if (i != size - 1) {
          result += ",";
        }
      }
    }
    return result;
  }

  @Override
  public void onResume() {
    super.onResume();

    // getPainpointList();
  }

  @Override
  public void onPause() {
    super.onPause();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
  }

  private int totalMonth;

  private void checkBabyAge() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null && Tools.isNotEmpty(lu.machine)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      try {
        Calendar bef = Calendar.getInstance();
        bef.setTime(sdf.parse(lu.machine.dob));

        int month = Calendar.getInstance().get(Calendar.MONTH)
            - bef.get(Calendar.MONTH);

        int year = Calendar.getInstance().get(Calendar.YEAR)
            - bef.get(Calendar.YEAR);

        totalMonth = year * 12 + month;
        if (totalMonth == 0) {
          totalMonth = 1;
        }

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
  }

  private Dialog notificationTipDlg;
  long prelongTim = 0;
  private boolean hasFinish;

  public void showNotificationTipDialog() {
    LayoutInflater inflater = getLayoutInflater();
    final View layout = inflater.inflate(R.layout.painpoint_dlg, null);// 获取自定义布局

    TextView tv_babyage = (TextView) layout.findViewById(R.id.tv_babyage);
    if (tv_babyage != null
        && Tools.isNotEmpty(LeXiaoXiaoBanApp.getInstance().kidAge)) {
      tv_babyage.setText("您的宝贝的年龄是" + LeXiaoXiaoBanApp.getInstance().kidAge
          + ",");
    }

    notificationTipDlg = new Dialog(this, R.style.custom_dialog);
    notificationTipDlg.setContentView(layout);
    notificationTipDlg.setCancelable(false);
    notificationTipDlg.show();

    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        if (hasFinish) {
          if (notificationTipDlg != null) {
            notificationTipDlg.dismiss();
            notificationTipDlg = null;
          }

          mPainPointListSelect = new ArrayList<PainPointItem>();
          for (PainPointItem ppi : mPainPointList) {
            if (mSelectedPainPointIds.contains(ppi.id)) {
              ppi.selected = true;
              mPainPointListSelect.add(ppi);
            }
          }

          String jsonString = JsonSerializer.getInstance().serialize(
              mPainPointListSelect);
          LePreference.getInstance().save("selectedpainpoint", jsonString);

          Intent intent = new Intent(PainPointSelectActivity.this,
              MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(intent);
          finish();
        }
      }
    }, 3000);
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.view.View.OnClickListener#onClick(android.view.View)
   */
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.commit_btn:

      showNotificationTipDialog();

      prelongTim = System.currentTimeMillis();

      hasFinish = false;

      new CustomAsyncTask(PainPointSelectActivity.this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          hasFinish = true;
          long curTime = System.currentTimeMillis();

          if ((curTime - prelongTim) > 3200) {
            if (notificationTipDlg != null) {
              notificationTipDlg.dismiss();
              notificationTipDlg = null;
            }

            if (result.isSuccess()) {

              mPainPointListSelect = new ArrayList<PainPointItem>();
              for (PainPointItem ppi : mPainPointList) {
                if (mSelectedPainPointIds.contains(ppi.id)) {
                  ppi.selected = true;
                  mPainPointListSelect.add(ppi);
                }
              }

              String jsonString = JsonSerializer.getInstance().serialize(
                  mPainPointListSelect);
              LePreference.getInstance().save("selectedpainpoint", jsonString);

              Intent intent = new Intent(activity, MainActivity.class);
              intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              startActivity(intent);
              finish();
            }
          }
        }

        @Override
        public ResponseResult doInbackground(Activity activity) {
          HashMap<String, Object> param_ = new HashMap<String, Object>();
          String ids = convertList2String(mSelectedPainPointIds);
          Log.e(TAG, ids);

          if (mGlobalLeUser != null) {
            param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
          } else {
            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
            if (lu == null) {
              lu = Tools.restoreLeUser();
            }
            param_.put(HttpUtils.TAG_SNO_I, lu.sno);
          }

          param_.put("habit_ids", ids);
          return HttpUtils.startRequest(HttpUtils.API_URL
              + HttpUtils.UPDATE_PAINPOINT_POST, param_,
              HttpUtils.TAG_POST_REQUEST);
        }
      }).execute();

      break;
    default:
      break;
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent returnedIntent) {
    super.onActivityResult(requestCode, resultCode, returnedIntent);
    switch (requestCode) {
    case 111:
      if (resultCode == RESULT_OK) {
        getPainpointList();
      }
      break;

    }
  }
}
